//
//  TJAccountViewModle.m
//  TJSinaWeiBo_OC
//
//  Created by 唐后能 on 16/4/19.
//  Copyright © 2016年 itheima. All rights reserved.
//

#import "TJAccountViewModle.h"
#import "TJNetWorkTool.h"
@implementation TJAccountViewModle
// 获取全局共享单例.
+(instancetype)shareAccountViewModle{

    static TJAccountViewModle *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        // 单例,只在运行程序时加载一次.
        instance.account = [instance loadAccount];
    });

    return instance;
}

// 判断是否登录.
- (BOOL)isLogin {

    return self.account != nil;
}


// 加载用户信息.
- (TJAcount*)loadAccount{
    
    TJAcount * account = (TJAcount*)[NSKeyedUnarchiver unarchiveObjectWithFile:TJAccountFilePath];
    NSComparisonResult result = [account.dueDate compare:[NSDate date]];
//    TJLog(@"%@",TJAccountFilePath);
    if (account != nil && result==NSOrderedDescending) {
        return account;
    }
    return nil;
}


// 加载授权token.
-(void)loadAccess_token:(NSString*)code andCallBack:(void(^)(NSError *error)) callBack {

    // 1,准备urlString.
    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
    
    // 2,授权参数.
    NSDictionary *parameters = @{
                                 @"client_id": client_id,
                                 @"client_secret": client_secret,
                                 @"grant_type": grant_type,
                                 @"code": code,
                                 @"redirect_uri": redirect_uri
                                 };
    // 3,发送请求.
    [[TJNetWorkTool shareNetWorkTool] POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary* responseObject) {
        
//        TJLog(@"%@",responseObject);
        // 请求成功
        // 1,将字典转成模型.
        TJAcount *account = [TJAcount acountWithDict:responseObject];
        // 同时给自己的account属性赋值.
        self.account = account; // 加载完会跳到欢迎,在跳到主界面(那时要为登录状态了).
        // 2,保存数据.
        [NSKeyedArchiver archiveRootObject:account toFile:TJAccountFilePath];
        //    TJLog(@"%@",TJAccountFilePath);
        

        // 2,成功回调.
        callBack(nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败.
        TJLog(@"获取用户信息失败:%@",error);
        // 给isLogin赋值为NO.
        self.isLogin = NO;
        callBack(error);
    }];
}


@end
